# -*- codeing = utf-8 -*-
# @Time : 2022/8/5 23:06
# @Author : ZN
# @Email : 747723508@qq.com
# @File : permission.py
# @Software: PyCharm
from functools import update_wrapper

from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission
from rest_framework.response import Response


class TeacherPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user  # 当前请求的用户信息
        # 判断身份，查询用户在不在老师这个分组里面
        group = Group.objects.filter(name='老师').first()
        user_groups = user.groups.all()
        return user.is_superuser or group in user_groups


class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):
        # 操作的用户必须是当前登陆的用户
        user = request.user
        return user.id == int(view.kwargs['pk'])


class ActiveUserPPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user
        return user.id == int(request.data.get('user'))


class RootPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user
        return user.is_superuser


# 更改权限的装饰器
def wrap_permisssion(*permissions, validate_permisssion=True):
    def decorator(func):
        def wrapper(self, request, *args, **kwargs):
            self.permission_classes = permissions
            if validate_permisssion:
                self.check_permissions(request)
            return func(self, request, *args, **kwargs)

        return update_wrapper(wrapper, func)

    return decorator


def auto_user(func):  # 自动获取当前登陆的用户 ，作为接口的创建者
    def wrapper(self, request, *args, **kwargs):
        request.POST._mutable = True  # 让请求参数可以被修改
        request.data['user'] = request.user.id

        return func(self, request, *args, **kwargs)  # 返回的是原本create函数中的参数

    return wrapper


def update_auto_user(func):
    def wrapper(self, request, *args, **kwargs):
        # 判断当前用户是不是这个数据的创建者
        # 设：文章id为1，作者为3，当前登陆用户为5
        # 查询到所有没有被逻辑删除的文章数据集，需要修改id为1的文章，则判断作者id==当前登陆的用户id，false则返回您没有操作的权限
        res = self.get_queryset().filter(id=kwargs['pk'], user=request.user)
        if not res:
            return Response({'detail': '您没有修改的权限'})
        # 修改内容不可以修改作者，只能是当前登陆的用户
        request.POST._mutable = True  # 让请求参数可以被修改
        request.data['user'] = request.user.id
        return func(self, request, *args, **kwargs)

    return wrapper


def destroy_auto_user(func): #删除权限装饰器
    def wrapper(self, request, *args, **kwargs):
        res = self.get_queryset().filter(id=kwargs['pk'], user=request.user)
        if not res:
            return Response({'detail': '您没有删除的权限'})
        return func(self, request, *args, **kwargs)

    return wrapper
